﻿
using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using BuyWithoutLose.Models;
using BuyWithoutLoseMoney;
using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;

namespace BuyWithoutLose.Controllers
{
    public class ZhiFuController : Controller
    {
        private readonly ILogger _logger;
        private readonly IRepository<Order, int> _orderRepostitory;
        private readonly IRepository<User, int> _userRepostitory;
        private readonly IRepository<UserAddress, int> _userAddressRepostitory;
        private readonly IRepository<BuyWithoutLoseMoney.Core.Models.Product, int> _productRepostitory;
        private readonly IRepository<ProductPic, int> _productPicRepostitory;
        public ZhiFuController(ILogger<DingDanController> logger
            , IRepository<Order, int> orderRepostitory, IRepository<User, int> userRepository,
             IRepository<UserAddress, int> userAddressRepostitory, IRepository<ProductPic, int> productPicRepostitory,
            IRepository<BuyWithoutLoseMoney.Core.Models.Product, int> productRepostitory
            )
        {
            _logger = logger;
            _orderRepostitory = orderRepostitory;
            _userRepostitory = userRepository;
            _userAddressRepostitory = userAddressRepostitory;
            _productPicRepostitory = productPicRepostitory;
            _productRepostitory = productRepostitory;
        }

        #region 支付页
        public async Task<IActionResult> Index(int id)
        {
            var userName = HttpContext.User.Claims.First().ValueType;
            var userid = int.Parse(userName);
            var user = _userRepostitory.GetAllList().Where(x => x.Id == userid).FirstOrDefault();
            ViewBag.User = user;
            var userAddress = _userAddressRepostitory.GetAllList();
            ViewBag.Address = userAddress;
            var order = _orderRepostitory.GetAll().Where(x=>x.Id==id).FirstOrDefault();
            return View(order);
        }
        [HttpPost]
        public IActionResult Index(string orderTitle, string orderNo, string orderMoney)
        {

            //1 记得格式转换
            //应用私钥
            string privateKey = "MIIEpAIBAAKCAQEAsvwiaO7aCHGyeI2ydvDxB7laE+ZiAoRlJsb29vOyB22XlCNia86EKg2ftBoocJvw6xrb5F4Qq081fhnIyrn7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dn2u576Ma3wquyAFosCVyO/HC7jz3mbs0VpBATkDvOH40dRV+hWJ0CgYEAsi59T3mZx4Vrg6zp6e68vO1hAi6HtLCoguTi+XzNkRmFGh0LskQrCEH7HaPQoYIxsHlXsI81Ms2Bg2lTmR99UNPepYHVtWMAXgmy4FFCLSWHAoteyD3NRRg77UL+mU9j9IAB/bLHp8kNiPiTKAB4gSebpK6kTxHHISoVxS0oP80CgYBJuzUN/a4j877NAfDtawIrZ0TEVpUb5/PS5Ugb2ZuX5s3+Fmt6MFvIQB3ygREJ5wOiAND/mOAETIpLBE7zv4GwsYpV0wXkRn44SSunHxLML37u9U2y857SGlxH6mYTRjGB9pfV5Z+OrA/BMa/NkM+7fYgCnXlvAcONKBQ3+lMDAg==";   
            
            //支付宝公钥
            string alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjRJiGhk2FAbqg9TsN/FJE83CVCjbDqBNnlwK/G29mSmJof7kGxSGLctwWoM2cT9VPLVwEOhSsGyEOaqwYNFs6UtEDQxBsCWhsymz/CrJTKmQ0/NiT141iyipY7wx3bJx05oFgydChqonlavu4BYLHRqAzl5cs6VDkwU+AUtgbTgUoV9ES8YZGJNvAqwHOOTDxrL38Rgihd58rTm8H8WMOAdZAgo8oelxN7GUgaMOJWKG3U8Ux3DJn6ontYriJRxbQZTXEhz5/8h0niUCk9EkCkwnsBBcLyNCT0ByPZToByBI3bEQun5nvBxcGIPPPtwFiOsSj2/JQxFQ9VNM/PrMpwIDAQAB";  //2 去网页上找
            AlipayConfig alipayConfig = new AlipayConfig
            {
                ServerUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do",   //3 支付宝网关地址
                AppId = "2021000122667620",            //4 APPID
                PrivateKey = privateKey,
                Format = "json",
                AlipayPublicKey = alipayPublicKey,
                Charset = "UTF-8",
                SignType = "RSA2",

            };
            IAopClient alipayClient = new DefaultAopClient(alipayConfig);
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

            // 设置同步回调地址
            request.SetReturnUrl("http://localhost:1695/yonghuzhongxin/index");
            // 设置异步通知接收地址
            request.SetNotifyUrl("http://localhost:1695/zhifu/index");

            AlipayTradePagePayModel model = new AlipayTradePagePayModel
            {
                OutTradeNo = orderNo,
                TotalAmount = orderMoney,
                Subject = orderTitle,
                ProductCode = "FAST_INSTANT_TRADE_PAY"

            };
            request.SetBizModel(model);
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);

            if (!response.IsError)
            {
                ViewBag.Temp = response.Body;
            }
            return View();
        }
        #endregion

        #region 订单地址
        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Edit(int id)
        {
            var order = _orderRepostitory.GetAll().Where(x=>x.Id==id).FirstOrDefault();
            var pro = _productRepostitory.GetAll().Where(x=>x.Id==int.Parse(order.Ext1)).FirstOrDefault();
            ViewBag.Product = pro;
            var productPic = _productPicRepostitory.GetAllList().Where(x=>x.ProductId==pro.Id&&x.PicType==1).FirstOrDefault();
            ViewBag.ProductPic = productPic;
            //var userName = HttpContext.User.Claims.First().ValueType;
            //var userid = int.Parse(userName);
            //var user = _userRepostitory.GetAllList().Where(x => x.Id == userid).FirstOrDefault();
            //ViewBag.User = user;
            var userAddress = _userAddressRepostitory.GetAllList();
            ViewBag.Address = userAddress;
            return View(order);
        }
        [HttpPost]
        public async Task<IActionResult> Edit(Order order)
        {
            if (ModelState.IsValid)
            {
                var o = _orderRepostitory.FirstOrDefault(x=>x.Id==order.Id);
                o.ReceivingAddress= order.ReceivingAddress;
                await _orderRepostitory.UpdateAsync(o);
                return Json(new { isSuccess = true, msg = "请等待，正在跳转！" });
                
            }
            return Json(new { isSuccess = false, msg = "失败" });
        }
        #endregion
    }
}
